package model

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"strconv"
	"time"
)

var _ SmsSeckillSessionModel = (*customSmsSeckillSessionModel)(nil)

type (
	// SmsSeckillSessionModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSmsSeckillSessionModel.
	SmsSeckillSessionModel interface {
		smsSeckillSessionModel
		FindByPage(ctx context.Context, page, pageSize int64) ([]SmsSeckillSession, error)
		FindAll(ctx context.Context) ([]SmsSeckillSession, error)
	}

	customSmsSeckillSessionModel struct {
		*defaultSmsSeckillSessionModel
	}
)

func (c *customSmsSeckillSessionModel) FindAll(ctx context.Context) ([]SmsSeckillSession, error) {
	now := time.Now()
	endTime := now.Add(24 * time.Hour).Add(24 * time.Hour)
	start := now.Format("2006-01-02 15:04:05")
	end := endTime.Format("2006-01-02 15:04:05")
	var sessions []SmsSeckillSession
	query := fmt.Sprintf("SELECT * FROM sms_seckill_session WHERE start_time BETWEEN ? AND ?")
	err := c.conn.QueryRowsCtx(ctx, &sessions, query, start, end)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	return sessions, nil
}

func (c *customSmsSeckillSessionModel) FindByPage(ctx context.Context, page, pageSize int64) ([]SmsSeckillSession, error) {
	offset := pageSize * (page - 1)
	query := fmt.Sprintf("SELECT * FROM sms_seckill_session LIMIT ? OFFSET ?")
	var list []SmsSeckillSession
	err := c.conn.QueryRowsCtx(ctx, &list, query, strconv.FormatInt(pageSize, 10), offset)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	return list, nil
}

// NewSmsSeckillSessionModel returns a model for the database table.
func NewSmsSeckillSessionModel(conn sqlx.SqlConn) SmsSeckillSessionModel {
	return &customSmsSeckillSessionModel{
		defaultSmsSeckillSessionModel: newSmsSeckillSessionModel(conn),
	}
}
